﻿using System;
using System.Linq;
using Pay.DTO;
using System.Collections.Generic;
using Pay.Data;
using Pay.Service.Cache;
using Pay.IService;

namespace Pay.Service {
	public class PayNotifyService : ServiceBase, IPayNotifyService, IDisposable {
		private IUnitOfWork _iUnitOfWork;

		public PayNotifyService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
			_iUnitOfWork = iUnitOfWork;
		}

		public pay_notify_dto GetByNo(string order_no) {
			return context.PayNotifys.FromCacheFirstOrDefault<PayNotify, pay_notify_dto>("PayNotify" + order_no);
		}


		public List<pay_notify_dto> Get() {
			var list = context.PayNotifys.ToList();
			var result = list.ProjectTo<PayNotify, pay_notify_dto>();
			return result;
		}

		public int Save(pay_notify_dto dto) {
			var model = context.PayNotifys.FirstOrDefault(c => c.OrderNo == dto.order_no);
			if (model == null) {
				model = new PayNotify();
				dto.id = Guid.NewGuid().ToString("N");
				dto.ToDtoObject(model);
				context.PayNotifys.Add(model);
			} else {
				model.Status = dto.status;
			}
			int result = _iUnitOfWork.Commit();
			return result;
		}

		public int Remove(string order_no) {
			var model = context.PayNotifys.FirstOrDefault(c => c.OrderNo == order_no);
			if (model != null) {
				context.PayNotifys.Remove(model);
				int result = _iUnitOfWork.Commit("PayNotify" + order_no);
				return result;
			}
			return 0;
		}
	}
}